package cn.z2huo.knowledge.concurrency.lock.reentrantlock.fair;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>非公平锁测试
 *
 * @author z2huo
 */
class FairLockTest {

    private static final int THREAD_COUNT = 4;

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock(true);

        IncrementData incrementData = new IncrementData(lock);

        Runnable runnable = () -> {
//            System.out.println("线程：" + Thread.currentThread().getName() + " run");
            incrementData.lockAndFastIncrease(Thread.currentThread().getName());
        };

        // 按顺序创建 4 个线程，并启动
        Thread[] threads = new Thread[THREAD_COUNT];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(runnable, "Thread-" + i);
        }
        for (int i = 0; i < threads.length; i++) {
            Thread thread = threads[i];
            thread.start();
        }

        ThreadUtil.sleep(2, TimeUnit.SECONDS);
        System.out.println("result is " + incrementData.getSum());
    }

}
